import React, { useEffect, useState } from 'react'
import { Modal, message, Skeleton, Cascader, Button, Image } from 'antd'
import ProForm, { ProFormDigit, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { UploadOutlined } from '@ant-design/icons'
import { addGoods, showGoods, updateGoods } from '@/services/goods'
import { getCategory } from '@/services/category'
import AliyunOSSUpload from '@/components/AliyunOSSUpload'
import Editor from '@/components/Editor';


export default function CreateOrEdit(props) {

  const { isModalVisible, isShowModal, actionRef, editId } = props
  // 状态改变 驱动 视图更新
  let [initialValues, setInitialValues] = useState(undefined)
  let [options, setOptions] = useState([])
  // 定义Form实例，用来操作表单
  const [ formObj ] = ProForm.useForm()
  const type = editId === undefined ? '添加' : '编辑'


  useEffect(async () => {
    const resCategory = await getCategory()
    if(resCategory.status === undefined) setOptions(resCategory)
    // 获取商品详情, 编辑的情况下，默认显示商品信息
    if(editId !== undefined) {
      const response = await showGoods(editId)
      const { pid, id } = response.category
      const defaultCategory = pid === 0 ? [id] : [pid, id]
      setInitialValues({...response, category_id: defaultCategory})
    }
  }, [])


  // 文件上传成功后，设置cover字段的值
  const setCoverKey = fileKey => formObj.setFieldsValue({'cover': fileKey})

  // 编辑器输入内容后，设置details字段的值
  const setDetails = content => formObj.setFieldsValue({'details': content})


  // 处理表单提交
  const handleSubmit = async values => {
    let response = undefined
    if(editId === undefined) {
      // 添加商品
      response = await addGoods( { ...values, category_id: values.category_id[1] } )
    } else {
      // 编辑 商品
      console.log(values)
      response = await updateGoods(editId, { ...values, category_id: values.category_id[1] })
    }
    if(response.status === undefined) {
      message.success(`${type}成功!`)
      // 刷新表格
      actionRef.current.reload()
      isShowModal(false)
    }
  }

  
  return (
    <Modal title={`${type}商品`} visible={isModalVisible} onCancel={() => {isShowModal(false)}} footer={null} destroyOnClose={true}>
      {
        initialValues === undefined && editId !== undefined ? 

        <Skeleton active paragraph={{ rows: 4 }} /> :

        <ProForm
          form={formObj}
          onFinish={ (values) => handleSubmit(values) }
          initialValues={ initialValues }
        >
          <ProForm.Item 
            label="分类" 
            name="category_id"
            rules={[{required:true, message:'请选择分类'}]}
          >
            <Cascader fieldNames={{label: 'name', value: 'id'}} options={options} placeholder="请选择分类" />
          </ProForm.Item>

          <ProFormText
            name="title"
            label="商品名"
            placeholder="请输入商品名"
            rules={[
              { required: true, message: '请输入商品名!' }
            ]}
          />
          <ProFormTextArea
            name="description"
            label="描述"
            placeholder="请输入描述"
            rules={[
              { required: true, message: '请输入描述!' }
            ]}
          />
          <ProFormDigit
            name="price"
            label="价格"
            placeholder="请输入价格"
            min={0}
            max={99999}
            rules={[
              { required: true, message: '请输入价格!' }
            ]}
          />
          <ProFormDigit
            name="stock"
            label="库存"
            placeholder="请输入库存"
            rules={[
              { required: true, message: '请输入库存!' }
            ]}
          />

          {/* 编辑时，初始化cover字段的值 ？ */}
          {/* <ProFormText name="cover" hidden/> */}

          <ProForm.Item
            name="cover"
            label="商品主图"
            rules={[{required:true, message:'请上传商品主图'}]}
          >
            {/* ProForm.Item的子元素div是受控组件 不加div的话，AliyunOSSUpload为受控组件，检测到Upload组件只设置了cover字段为文件的key值，而没有检测到真正的文件， antd源码就会报错 */}
            <div>
              <AliyunOSSUpload accept="image/*" setCoverKey={setCoverKey} showUploadList={true}>
                <Button icon={<UploadOutlined />}>点击上传</Button>
              </AliyunOSSUpload>
              {
                initialValues === undefined || !initialValues.cover_url ? '' : 
                <Image width={200} src={initialValues.cover_url}/>
              }
            </div>
          </ProForm.Item>

          <ProForm.Item
            name="details"
            label="详情"
            rules={[{required:true, message:'请输入商品详情'}]}
          >
            <Editor 
              setDetails={setDetails} 
              content={initialValues === undefined ? '' : initialValues.details}
            />
          </ProForm.Item>

        </ProForm>
      }
    </Modal>
  )
  
}
